package solutions.ferpa.ztest.rest.action;

import br.com.telescope.adsrt.lib.BaseRuntime;
import br.com.telescope.adsrt.lib.ServletRuntime;
import br.com.telescope.auth.AdsrtSession;
import br.com.telescope.auth.Session;
import br.com.telescope.auth.User;
import solutions.ferpa.ztest.ent.EntBilhetesEntrada;
import solutions.ferpa.ztest.rest.RestService;
import solutions.ferpa.ztest.rest.model.res.AuthLogoutRQ;
import solutions.ferpa.ztest.rest.model.res.AuthLogoutRS;

@RestAction(action = "logout", rqType = AuthLogoutRQ.class, rsType = AuthLogoutRS.class)
public class AuthLogout extends RestService<AuthLogoutRQ, AuthLogoutRS> {

    public AuthLogout(BaseRuntime ctx) {
        super(ctx);
    }

    @Override
    public AuthLogoutRS call() throws Exception {
        AuthLogoutRS rs = new AuthLogoutRS();
        rs.setResource(Boolean.FALSE);

        try {
            AdsrtSession session = (AdsrtSession) ctx.getSession();
            // Zera o menu (vai reconstruir só com acessos públicos)
            session.setObject("MENU", null);
            // Verifica se existe um bilhete de entrada válido
            String bilhete = ((ServletRuntime) ctx).getCookieValue(session.getCookieName());
            try {
                EntBilhetesEntrada bil = new EntBilhetesEntrada(ctx);
                bil.findByCodigo(bilhete);
                bil.del();
            } catch (Exception e) {
                // Não encontrou - Ignora!
            }
            // Remove o bilhete de entrada
            ((ServletRuntime) ctx).delCookie(bilhete);
            // Apaga informações do usuário
            User user = (User) session.getObject(Session.USER);
            rs.setResource(new Boolean(new Long(user.getId()).longValue() == bindRequest(AuthLogoutRQ.class).getUserId()));
            session.logout();
        } catch (Throwable e){
            rs.getAlerts().addError(e.getMessage());
        }

        return rs;
    }

}